// 安全进程管理服务 - 仅使用safe Rust

use std::sync::{Arc, Mutex, Condvar}; use std::sync::atomic::Ordering;
use std::collections::HashMap;
use std::thread;
use std::time::Duration;
use log::{info, warn, error};

use super::{Capability};
use super::exokernel_get_cpu_time_slice;
use super::mem_service::MemoryService;

// 进程ID类型
pub type ProcessId = u32;

// 进程状态
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessState {
    New,
    Ready,
    Running,
    Blocked,
    Terminated,
}

// 进程控制块
pub struct ProcessControlBlock {
    pid: ProcessId,
    state: ProcessState,
    priority: u8,
    time_used: u64,
    cpu_time_slice: u32,
    // 其他进程相关信息
}

impl ProcessControlBlock {
    // 创建新的进程控制块
    pub fn new(pid: ProcessId, priority: u8) -> Self {
        ProcessControlBlock {
            pid,
            state: ProcessState::New,
            priority,
            time_used: 0,
            cpu_time_slice: 100, // 默认100ms
        }
    }

    // 获取进程ID
    pub fn pid(&self) -> ProcessId {
        self.pid
    }

    // 获取进程状态
    pub fn state(&self) -> ProcessState {
        self.state
    }

    // 设置进程状态
    pub fn set_state(&mut self, new_state: ProcessState) {
        self.state = new_state;
    }

    // 获取优先级
    pub fn priority(&self) -> u8 {
        self.priority
    }

    // 设置优先级
    pub fn set_priority(&mut self, new_priority: u8) {
        self.priority = new_priority;
    }

    // 更新使用时间
    pub fn update_time_used(&mut self, time_ms: u64) {
        self.time_used += time_ms;
    }

    // 获取CPU时间片
    pub fn cpu_time_slice(&self) -> u32 {
        self.cpu_time_slice
    }

    // 设置CPU时间片
    pub fn set_cpu_time_slice(&mut self, time_slice: u32) {
        self.cpu_time_slice = time_slice;
    }
}

// 进程调度器
pub struct Scheduler {
    ready_queue: Vec<ProcessId>,
    running_process: Option<ProcessId>,
    last_switch_time: u64,
}

impl Scheduler {
    // 创建新的调度器
    pub fn new() -> Self {
        Scheduler {
            ready_queue: Vec::new(),
            running_process: None,
            last_switch_time: 0,
        }
    }

    // 添加进程到就绪队列
    pub fn enqueue(&mut self, pid: ProcessId) {
        // 简单的优先级队列实现（这里使用FIFO）
        self.ready_queue.push(pid);
    }

    // 从就绪队列取出进程
    pub fn dequeue(&mut self) -> Option<ProcessId> {
        self.ready_queue.pop()
    }

    // 设置运行中的进程
    pub fn set_running(&mut self, pid: ProcessId) {
        self.running_process = Some(pid);
        // 记录切换时间
        self.last_switch_time = self.get_current_time_ms();
    }

    // 获取运行中的进程
    pub fn get_running(&self) -> Option<ProcessId> {
        self.running_process
    }

    // 检查是否需要切换进程
    pub fn should_switch(&self, current_process: &ProcessControlBlock) -> bool {
        let current_time = self.get_current_time_ms();
        let elapsed_time = current_time - self.last_switch_time;
        
        // 如果进程时间片用完或者有更高优先级的进程，需要切换
        elapsed_time >= current_process.cpu_time_slice as u64 || !self.ready_queue.is_empty()
    }

    // 获取当前时间（毫秒）
    fn get_current_time_ms(&self) -> u64 {
        // 这里简化实现，实际应使用系统时间
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as u64
    }
}

// 进程管理服务
pub struct ProcessService {
    cpu_cap: Capability,
    memory_service: Arc<Mutex<MemoryService>>,
    scheduler: Scheduler,
    processes: HashMap<ProcessId, Mutex<ProcessControlBlock>>,
    next_pid: ProcessId,
    initialized: std::sync::atomic::AtomicBool,
    exit_requested: std::sync::atomic::AtomicBool,
    scheduler_thread: Option<std::thread::JoinHandle<()>>,
    // 用于同步的条件变量
    condvar: Arc<(Mutex<bool>, Condvar)>,
}

impl ProcessService {
    // 创建新的进程服务
    pub fn new(cpu_cap: Capability, memory_service: Arc<Mutex<MemoryService>>) -> Result<Self, String> {
        if !cpu_cap.is_acquired() {
            return Err("CPU capability not acquired".to_string());
        }

        Ok(ProcessService {
            cpu_cap,
            memory_service,
            scheduler: Scheduler::new(),
            processes: HashMap::new(),
            next_pid: 1, // 从1开始分配PID
            initialized: std::sync::atomic::AtomicBool::new(false),
            exit_requested: std::sync::atomic::AtomicBool::new(false),
            scheduler_thread: None,
            condvar: Arc::new((Mutex::new(false), Condvar::new())),
        })
    }

    // 启动进程服务
    pub fn start(&mut self) -> Result<(), String> {
        if self.initialized.load(Ordering::SeqCst) {
            return Err("Process service already started".to_string());
        }
        
        self.initialized.store(true, Ordering::SeqCst);
        
        // 克隆条件变量和self
        let condvar_clone = self.condvar.clone();
        let mut_svc = Arc::new(Mutex::new(self.clone()));
        
        // 启动调度器线程
        self.scheduler_thread = Some(std::thread::spawn(move || {
            let (lock, _cvar) = &*condvar_clone;
            
            loop {
                // 检查退出条件
                if let Some(mut svc) = mut_svc.lock() {
                    if svc.exit_requested.load(Ordering::SeqCst) {
                        break;
                    }
                    
                    // 执行调度
                    if let Err(err) = svc.schedule() {
                        error!("Scheduler error: {}", err);
                    }
                }
                
                // 短暂休眠以避免CPU占用过高
                std::thread::sleep(Duration::from_millis(10));
            }
        }));
        
        Ok(())
    }

    // 创建进程
    pub fn create_process(&mut self, priority: u8) -> Result<ProcessId, String> {
        if !self.initialized {
            return Err("Process service not initialized".to_string());
        }

        // 分配PID
        let pid = self.next_pid;
        self.next_pid += 1;

        // 创建PCB
        let pcb = ProcessControlBlock::new(pid, priority);
        self.processes.insert(pid, Mutex::new(pcb));

        info!("Created process with PID {}", pid);
        Ok(pid)
    }

    // 销毁进程
    pub fn destroy_process(&mut self, pid: ProcessId) -> Result<bool, String> {
        if !self.initialized {
            return Err("Process service not initialized".to_string());
        }

        // 查找进程
        if !self.processes.contains_key(&pid) {
            return Err("Process not found".to_string());
        }

        // 获取进程控制块
        let mut pcb = self.processes.get(&pid).unwrap().lock().unwrap();
        
        // 检查进程状态
        if pcb.state() != ProcessState::Terminated {
            // 将进程标记为终止
            pcb.set_state(ProcessState::Terminated);
        }

        // 从进程表中移除
        self.processes.remove(&pid);

        // 如果是当前运行的进程，需要调度
        if let Some(running_pid) = self.scheduler.get_running() {
            if running_pid == pid {
                self.scheduler.running_process = None;
            }
        }

        info!("Destroyed process with PID {}", pid);
        Ok(true)
    }

    // 启动进程
    pub fn start_process(&mut self, pid: ProcessId) -> Result<bool, String> {
        if !self.initialized {
            return Err("Process service not initialized".to_string());
        }

        // 查找进程
        let pcb = match self.processes.get(&pid) {
            Some(pcb) => pcb,
            None => return Err("Process not found".to_string()),
        };

        // 更新进程状态
        {
            let mut p = pcb.lock().unwrap();
            if p.state() == ProcessState::New || p.state() == ProcessState::Blocked {
                p.set_state(ProcessState::Ready);
                // 添加到就绪队列
                self.scheduler.enqueue(pid);
                info!("Started process with PID {}", pid);
                return Ok(true);
            }
        }

        warn!("Cannot start process with PID {}: invalid state", pid);
        Ok(false)
    }

    // 停止进程
    pub fn stop_process(&mut self, pid: ProcessId) -> Result<bool, String> {
        if !self.initialized {
            return Err("Process service not initialized".to_string());
        }

        // 查找进程
        let pcb = match self.processes.get(&pid) {
            Some(pcb) => pcb,
            None => return Err("Process not found".to_string()),
        };

        // 更新进程状态
        {
            let mut p = pcb.lock().unwrap();
            if p.state() == ProcessState::Running || p.state() == ProcessState::Ready {
                p.set_state(ProcessState::Blocked);
                info!("Stopped process with PID {}", pid);
                return Ok(true);
            }
        }

        warn!("Cannot stop process with PID {}: invalid state", pid);
        Ok(false)
    }

    // 进程调度
    fn schedule(&mut self) {
        // 检查当前运行的进程是否需要切换
        if let Some(running_pid) = self.scheduler.get_running() {
            if let Some(pcb) = self.processes.get(&running_pid) {
                let p = pcb.lock().unwrap();
                if self.scheduler.should_switch(&p) {
                    // 让出CPU
                    drop(p); // 释放锁
                    self.yield_cpu(running_pid);
                }
            }
        }

        // 如果没有运行中的进程，且就绪队列不为空，选择一个进程运行
        if self.scheduler.get_running().is_none() && !self.scheduler.ready_queue.is_empty() {
            if let Some(next_pid) = self.scheduler.dequeue() {
                self.run_process(next_pid);
            }
        }
    }

    // 运行进程
    fn run_process(&mut self, pid: ProcessId) {
        if let Some(pcb) = self.processes.get(&pid) {
            let mut p = pcb.lock().unwrap();
            if p.state() == ProcessState::Ready {
                p.set_state(ProcessState::Running);
                
                // 设置为当前运行的进程
                drop(p); // 释放锁
                self.scheduler.set_running(pid);
                
                // 获取CPU时间片
                self.acquire_cpu_time_slice(pid);
                
                info!("Started running process with PID {}", pid);
            }
        }
    }

    // 让出CPU
    fn yield_cpu(&mut self, pid: ProcessId) {
        if let Some(pcb) = self.processes.get(&pid) {
            let mut p = pcb.lock().unwrap();
            if p.state() == ProcessState::Running {
                p.set_state(ProcessState::Ready);
                // 添加回就绪队列
                self.scheduler.enqueue(pid);
                // 清除当前运行的进程
                self.scheduler.running_process = None;
                info!("Process with PID {} yielded CPU", pid);
            }
        }
    }

    // 获取CPU时间片
    fn acquire_cpu_time_slice(&self, pid: ProcessId) {
        if let Some(pcb) = self.processes.get(&pid) {
            let p = pcb.lock().unwrap();
            let time_slice = p.cpu_time_slice();
            let cap_id = self.cpu_cap.id();
            
            unsafe {
                exokernel_get_cpu_time_slice(cap_id, time_slice);
            }
            
            info!("Process with PID {} acquired {}ms CPU time slice", pid, time_slice);
        }
    }
}

// 为ProcessService实现Clone（用于线程安全）
impl Clone for ProcessService {
    fn clone(&self) -> Self {
        // 创建新的进程服务实例，共享资源
        ProcessService {
            cpu_cap: self.cpu_cap.clone(),
            memory_service: Arc::clone(&self.memory_service),
            scheduler: self.scheduler.clone(),
            processes: self.processes.clone(),
            next_pid: self.next_pid,
            initialized: std::sync::atomic::AtomicBool::new(self.initialized.load(std::sync::atomic::Ordering::Relaxed)),
            exit_requested: std::sync::atomic::AtomicBool::new(self.exit_requested.load(std::sync::atomic::Ordering::Relaxed)),
            scheduler_thread: None, // 不克隆线程句柄
            condvar: Arc::clone(&self.condvar),
        }
    }
}

// 为Scheduler实现Clone
impl Clone for Scheduler {
    fn clone(&self) -> Self {
        Scheduler {
            ready_queue: self.ready_queue.clone(),
            running_process: self.running_process,
            last_switch_time: self.last_switch_time,
        }
    }
}

// 为Capability实现Clone
impl Clone for Capability {
    fn clone(&self) -> Self {
        Capability {
            id: self.id,
            acquired: self.acquired,
        }
    }
}